<template>
    <div class="app-container">
        <div v-show="type == 0 || type == 2">
            <el-row>
                <el-col :span="24">
                    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                        label-width="68px">
                        <el-form-item label="合同名称" prop="contractName">
                            <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable
                                @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <el-form-item label="签订时间">
                            <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd"
                                type="daterange" range-separator="-" start-placeholder="开始日期"
                                end-placeholder="结束日期"></el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="mini"
                                @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>

                    <el-row :gutter="10" class="mb8">
                      <el-col :span="1.5">
                        <el-button  type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
                      </el-col>
                        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"
                            :columns="columns"></right-toolbar>
                    </el-row>
                  <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
                    <el-table v-loading="loading" height="450" :data="infoList"
                        @selection-change="handleSelectionChange" :row-style="{ height: '30px' }" border
                        :cell-style="{ padding: '0px' }" highlight-current-row>
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="序号" type="index" align="center" prop="index"
                            :index="indexMethod"></el-table-column>
                        <el-table-column label="合同名称" align="center" prop="contractName" width="180"
                            :show-overflow-tooltip="true" v-if="columns[0].visible" />
                        <el-table-column label="合同金额" align="center" prop="contractAmount" :show-overflow-tooltip="true"
                            v-if="columns[1].visible" />
                        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true"
                            v-if="columns[2].visible" />
                        <el-table-column label="签订时间" align="center" prop="signingTime" :show-overflow-tooltip="true"
                            v-if="columns[3].visible">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.signingTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束时间" align="center" prop="endTime" :show-overflow-tooltip="true"
                            v-if="columns[4].visible">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="销售人员" align="center" prop="salespersonName" v-if="columns[5].visible"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="客户名称" align="center" prop="enterpriseName" width="180"
                            :show-overflow-tooltip="true" v-if="columns[6].visible" />
                        <el-table-column label="客户联系人" align="center" prop="customerContact" width="90"
                            :show-overflow-tooltip="true" v-if="columns[7].visible" />
                        <el-table-column label="联系电话" align="center" prop="telephone" :show-overflow-tooltip="true"
                            v-if="columns[8].visible" />
                        <el-table-column label="提供人" align="center" prop="provider" :show-overflow-tooltip="true"
                            v-if="columns[9].visible" />
                        <el-table-column label="提供来源" align="center" prop="provideSources" :show-overflow-tooltip="true"
                            v-if="columns[10].visible" />
                        <el-table-column label="业务费" align="center" prop="cost" :show-overflow-tooltip="true"
                            v-if="columns[11].visible" />
                        <el-table-column label="合同扫描件" align="center" prop="url" width="120" v-if="columns[12].visible">
                            <template slot-scope="scope">
                                <el-button @click.stop="queryUploadFile(scope.row.businessId)" size="small"
                                    v-if="scope.row.url != null && scope.row.url != ''" type="text">附件</el-button>
                                <el-button size="small" v-else type="text">无附件</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center" prop="state" v-if="columns[13].visible">
                            <template slot-scope="scope">
                                <dict-tag :options="dict.type.contract_state" :value="scope.row.state"
                                    :class="{ 'add-class': scope.row.state === '0', 'review-class': scope.row.state === '1', 'agree-class': scope.row.state === '2', 'cancel-class': scope.row.state === '3', }" />
                            </template>
                        </el-table-column>
                        <el-table-column label="创建人" align="center" prop="creationName" v-if="columns[14].visible"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="创建时间" align="center" prop="creationTime" :show-overflow-tooltip="true"
                            v-if="columns[15].visible">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
                            <template slot-scope="scope">
<!--                              :disabled="scope.row.state == '2' || (scope.row.state != '1' && (scope.row.contractReviewer === null || (scope.row.reviewer).indexOf(userName) === -1))-->
                              <el-button size="mini" type="text" icon="el-icon-user"
                                         @click="handleReview(scope.row, scope.$index + 1)" title="审核" v-if="scope.row.state=='1' && scope.row.reviewer==userName && scope.row.reviewResult === null"></el-button>
                                <el-button size="mini" type="text" icon="el-icon-view"  title="查看"
                                    @click="handleSubView(scope.row, scope.$index + 1)"></el-button>
                              <el-button size="mini" type="text" icon="el-icon-edit" title="修改"
                                         @click="handleUpdate(scope.row, scope.$index + 1)"  v-if="scope.row.state == '0' && scope.row.creationId==userId"></el-button>
                              <el-button size="mini" type="text" icon="el-icon-thumb" @click="handleSubmit(scope.row)" title="提交"
                                         v-if="scope.row.state == '0' && (scope.row.covenantId != '' && scope.row.covenantId != null)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                  </div>
                </el-col>
            </el-row>
        </div>
        <div v-if="type == 1">
            <Review @change="close" :index="index" :opt="edit" :uuid="uuid" :isClick="isClick" :id="id"
                :classId="classId" :cId="cId">
            </Review>
        </div>
      <div v-if="type == 3">
        <Operate @change="close"  :index="index" :opt="edit" :uuid="uuid" :isClick="isClick" :id="id"
                 :classId="classId" :cId="cId" >
        </Operate>
      </div>
        <el-dialog :title="titleClass" :visible.sync="openMainClass" width="500px" append-to-body>
            <el-form ref="formClass" :model="formClass" :inline="true">
                <el-form-item label="主分类" prop="classificationId" label-width="80px">
                    <treeselect v-model="formClass.classificationId" :options="optionData" placeholder="请选择主分类"
                        style="width: 202.5px" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitClassForm()">确 定</el-button>
                <el-button @click="cancelClass">关 闭</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <el-dialog :visible.sync="dialogVisiblePdf" append-to-body>
            <pdf v-for="item in pageTotal" :src="pdfUrl" :key="item" :page="item"></pdf>
        </el-dialog>
        <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body>
            <el-table :data="fileList">
                <el-table-column label="文件名称" align="center" prop="fileName" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
                    width="120">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-view"
                            @click.stop="handleView(scope.row)" title="查看"></el-button>
                        <el-button size="mini" type="text" icon="el-icon-download"
                            @click="handleDownload(scope.row.url, scope.row.fileName)" title="下载"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { listContractInfo, getContractInfo, updateContractState, addContractInfo, updateContractInfo, editMainClass, listContractReviewInfo } from "@/api/contract/info";
import MainType from "@/components/MainType/index";
import { listReviewInfo, getReviewInfo, delReviewInfo, addReviewInfo, updateReviewInfo } from "@/api/contract/reviewInfo";
import { listType } from "@/api/maintype/type";
import Review from "./review.vue"
import pdf from 'vue-pdf'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { download } from "@/utils/request";
import { queryFile, fileRemove } from "@/api/system/file";
import Operate from "./operate.vue";
export default {
    name: "ContractReview",
    dicts: ['contract_state'],
    components: {Operate, MainType, Review, pdf, Treeselect },
    data() {
        return {
            fileList: [],
            openFileList: false,
            userName: "",
            optionData: null,
            isTree: false,
            titleClass: "修改主分类",
            openMainClass: false,
            dateRange: [],
            type: 0,
            classId: "",
            userType: "1",
            sign: '1',
            opt: 'add',
            refreshKey: 0,
            id: '',
            obj: null,
            index: null,
            dialogVisible: false,
            dialogVisiblePdf: false,
            dialogImageUrl: '',
            dialogImageUrlPdf: '',
            pageTotal: null,
            newIndex: '',
            edit: 'edit',
            uuid: "",
            typeCode: 'contractInfo',
            // 遮罩层
            loading: true,
            isClick: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 【请填写功能名称】表格数据
            infoList: [],
            reviewList: [],
            userId: null,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            queryReviewParams: {
                pageNum: 1,
                pageSize: 15,
                reviewId: null,
                contractId: null,
                reviewerId: null,
                reviewer: null,
                reviewComments: null,
                reviewTime: null,
                reviewResult: null
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 15,
                contractId: null,
                classificationId: null,
                contractName: null,
                relatedContractId: null,
                relatedContractName: null,
                contractAmount: null,
                signingTime: null,
                endTime: null,
                enterpriseId: null,
                enterpriseName: null,
                customerAddress: null,
                customerContact: null,
                telephone: null,
                salespersonId: null,
                salespersonName: null,
                additionalTerms: null,
                belongTo: null,
                creationId: null,
                creationName: null,
                creationTime: null,
                operateTime: null,
                operateId: null,
                departmentId: null,
                departmentName: null,
                organizationId: null,
                organizationName: null,
                state: null
            },
            // 列信息
            columns: [
                { key: 0, label: `合同名称`, visible: true },
                { key: 1, label: `合同金额`, visible: true },
                { key: 2, label: `产品名称`, visible: true },
                { key: 3, label: `签订时间`, visible: true },
                { key: 4, label: `结束时间`, visible: true },
                { key: 5, label: `销售人员`, visible: true },
                { key: 6, label: `客户名称`, visible: true },
                { key: 7, label: `客户联系人`, visible: true },
                { key: 8, label: `联系电话`, visible: true },
                { key: 9, label: `提供人`, visible: true },
                { key: 10, label: `提供来源`, visible: true },
                { key: 11, label: `业务费`, visible: true },
                { key: 12, label: `合同扫描件`, visible: true },
                { key: 13, label: `状态`, visible: true },
                { key: 14, label: `创建人`, visible: true },
                { key: 15, label: `创建时间`, visible: true }
            ],
            // 表单参数
            form: {},
            formClass: {},
            // 表单校验
            rules: {},
            cId: ""
        };
    },
    created() {
        this.userName = this.$store.state.user.name;
        this.userId=this.$store.state.user.info.userId;
        this.listType();
        this.getList();
    },
    methods: {
        queryUploadFile(id) {
            queryFile(id, this.typeCode).then(response => {
                this.fileList = response.data;
                console.log(this.fileList)
            });
            this.openFileList = true;
        },
        handleDownload(fileUrl, fileName) {
            let params = {
                resource: fileUrl
            }
            download("/common/download/resource", params, fileName);
        },
        handleView(row) {
            if (row.url != null && row.url != '' && (row.url).indexOf('.pdf') !== -1) {
                this.handlePictureCardPreviewPdf(row.url);
            } else {
                this.handlePictureCardPreview(row.url);
            }
        },
        listType() {
            listType({ typeCode: 'contractInfo' }).then(res => {
                this.optionData = res.data;
            })
        },
        submitClassForm() {
            if (this.formClass.classificationId == "undefined" || this.formClass.classificationId == "" || this.formClass.classificationId == null) {
                this.$message.error("请选择主分类！");
            } else {
                const params = {
                    contractId: this.ids.toString(),
                    mainClassId: this.formClass.classificationId,
                };
                editMainClass(params).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.openMainClass = false;
                    this.getList();
                });
            }
        },
      /** 修改按钮操作 */
      handleUpdate(row, index) {
        this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
        this.edit = "edit";
        this.isClick = false;
        this.id = row.contractId;
        this.cId = row.contractId;
        this.type = 3
      },
      handleSubmit(row) {
        const contractInfo = {
          contractId: row.contractId
        }
        this.$modal.confirm('是否确认提交合同名称为"' + row.contractName + '"的数据项？').then(function () {
          updateContractState(contractInfo);
        }).then(() => {
          this.$modal.msgSuccess("提交成功");
          this.getList();
        }).catch(() => { });
      },
        cancelClass() {
            this.openMainClass = false;
            this.resetClass();
        },
        // 表单重置
        resetClass() {
            this.formClass = {
                classificationId: null,
            }
        },
        editMainClass() {
            if (this.ids.length == 0) {
                this.$message.error("请选择要修改的商机信息！");
            } else {
                this.openMainClass = true;
            }
        },
        getNode(data, node, obj) {
            this.queryParams.classificationId = data.id;
            this.classId = data.id;
            this.getList()
        },
        close() {
            this.type = 2;
            this.getList();
        },
        guid() {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
        },
        indexMethod(index) {
            return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        },
        /** 查询【请填写功能名称】列表 */
        getList() {
            this.loading = true;
            listContractReviewInfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                this.infoList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
      /** 新增按钮操作 */
      handleAdd() {
        this.uuid = this.guid();
        this.edit = "add";
        this.cId = this.uuid;
        this.isClick = true;
        this.type = 3;
      },
        // 表单重置
        reset() {
            this.form = {
                contractId: null,
                classificationId: null,
                contractName: null,
                relatedContractId: null,
                relatedContractName: null,
                contractAmount: null,
                signingTime: null,
                endTime: null,
                enterpriseId: null,
                enterpriseName: null,
                customerAddress: null,
                customerContact: null,
                telephone: null,
                salespersonId: null,
                salespersonName: null,
                additionalTerms: null,
                belongTo: null,
                creationId: null,
                creationName: null,
                creationTime: null,
                operateTime: null,
                operateId: null,
                departmentId: null,
                departmentName: null,
                organizationId: null,
                organizationName: null,
                delFlag: null,
                state: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        handlePictureCardPreview(url) {
            this.dialogImageUrl = url;
            this.dialogVisible = true;
        },
        handlePictureCardPreviewPdf(url) {
            this.pdfUrl = pdf.createLoadingTask(url)
            // 获取页码
            this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {
            })
            this.dialogImageUrlPdf = url;
            this.dialogVisiblePdf = true;
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.contractId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        handleSubView(row, index) {
            this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
            this.edit = "view";
            this.id = row.contractId;
            this.cId = row.contractId;
            this.type = 1;
        },
        handleReview(row, index) {
            this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
            this.edit = "review";
            this.id = row.contractId;
            this.cId = row.contractId;
            this.type = 1;
        },
    }
};
</script>
<style>
.add-class {
    color: orange;
}

.review-class {
    color: #409EFF;
}

.agree-class {
    color: #4CE778;
}

.cancel-class {
    color: red;
}
</style>
